package net.zjitc.android2019.ch5broadcast;

import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import net.zjitc.android2019.R;

/**
 * 1、Activity:  输入要拦截的号码,保存在SharedPreferences
 *
 * 2、订阅/注册广播: 静态注册和动态注册
 *  拨打电话时系统会发送action为android.intent.action.NEW_OUTGOING_CALL的广播
 *
 * 3、权限(静态添加和动态添加)
 *   android.permission.PROCESS_OUTGOING_CALLS
 *   允许程序监视、修改有关播出电话 *
 */
public class Ch5BroadcastActivity extends AppCompatActivity implements View.OnClickListener {
    EditText ed_phone;
    Button btn;
    /* 广播接收者*/
    MyReceiver myReceiver;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ch5_broadcast);
        ed_phone=findViewById(R.id.broadcast_ed_phone);
        btn=findViewById(R.id.broadcast_btn);
        btn.setOnClickListener(this);
        myReceiver=new MyReceiver();
        /* 动态添加权限*/
        String[] s={"android.permission.PROCESS_OUTGOING_CALLS"};
        ActivityCompat.requestPermissions(Ch5BroadcastActivity.this,s,1);
    }

    @Override
    public void onClick(View v) {
        /* 把输入框的内容保存在sp*/
        String phone=ed_phone.getText().toString();
        SharedPreferences sp=getSharedPreferences("phone",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("phone",phone);
        editor.commit();
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }


    /**
     * Activity生命周期方法，自动调用
     * 注册广播
     */
    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
        /* 参数1：广播接受者；参数2: 订阅哪个广播  */
        registerReceiver(myReceiver,intentFilter);
    }
    /**
     * Activity生命周期方法，自动调用
     * 销毁广播
     */
    @Override
    protected void onPause() {
        super.onPause();
        /* 本案例中使用动态注册广播的销毁广播 不合适*/
//        unregisterReceiver(myReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);
    }
}
